//获取应用实例
const app = getApp()
const db = wx.cloud.database()

Page({

    /**
     * 页面的初始数据
     */
    data: {
        formWarn: false,
        lostGoods: {
            time: "",//时间
            type: "捡到",
            place: "",//地点
            intro: "", //信息
            images: []  //图片
        },
        fileList: [],
        // date: '',
        show: false,
    },
    onChange(event) {
        this.setData({
            'lostGoods.type': event.detail,
        });
    },
    inputChange(e) {
        if (e.currentTarget.dataset.item == "place") {
            this.data.lostGoods.place = e.detail
        } else if (e.currentTarget.dataset.item == "intro") {
            this.data.lostGoods.intro = e.detail
        }
    },
    upload() {
        const that = this;
        try {
            this.data.fileList.map(item => {
                const filePath = item.url
                let name = new Date().getTime().toString()
                // 上传图片
                const cloudPath = "lostGoods/" + name + filePath.match(/\.[^.]+?$/)[0]
                wx.cloud.uploadFile({
                    cloudPath,
                    filePath,
                    success: res => {
                        // console.log('[上传文件] 成功：', res.fileID)
                        that.data.lostGoods.images.push(res.fileID)
                        if (that.data.lostGoods.images.length == that.data.fileList.length) {
                            wx.cloud.callFunction({
                                name: 'addlostGoods',
                                data: {
                                    data: that.data.lostGoods
                                }
                            }).then(res0 => {
                                wx.navigateTo({
                                    url: '/pages/homePage/lostGoods/lostGoods_details/lostGoods_details',
                                    success: function (res) {
                                        // 通过eventChannel向被打开页面传送数据
                                        res.eventChannel.emit('to_details', {
                                            mes: res0.result,
                                            status: "2"
                                        })
                                    }
                                })
                            })
                        }

                    },
                    fail: e => {
                        wx.showToast({
                            icon: 'none',
                            title: '上传失败',
                        })
                    }
                })
            })
        } catch (error) {
            console.error(error);
        }
    },
    submit() {
        this.data.lostGoods.merchant = app.globalData.userInfo.nickName
        this.data.lostGoods.avatarUrl = app.globalData.userInfo.avatarUrl
        for (let item in this.data.lostGoods) {
            if (!this.data.fileList || item != "images" && !this.data.lostGoods[item]) {
                // console.log(item)
                this.setData({
                    formWarn: true
                })
                return setTimeout(() => {
                    this.setData({
                        formWarn: false
                    })
                }, 2000)
            }
        }

        wx.showLoading({
            mask: true,
            title: '上传中',
        })
        this.upload()
    },

    //time
    onDisplay() {
        this.setData({ show: true });
    },
    onClose() {
        this.setData({ show: false });
    },
    formatDate(date) {
        date = new Date(date);
        return `${date.getFullYear()}/${date.getMonth() + 1}/${date.getDate()}`;
    },
    onConfirm(event) {
        this.setData({
            show: false,
            'lostGoods.time': this.formatDate(event.detail),
        });
    },
    // 图片
    afterRead(event) {
        const { file } = event.detail;
        const that = this;
        wx.chooseImage({
            count: 3,
            sizeType: ['compressed'],
            sourceType: ['album', 'camera'],
            success: function (res) {
                const { fileList = [] } = that.data;
                res.tempFilePaths.map(item => {
                    fileList.push({ ...file, url: item, isImage: true });
                })
                that.setData({
                    fileList
                })
            },
            fail: e => {
                console.error(e)
            }
        })
    },
    deleteImage(e) {
        // console.log(e.detail.index)
        const { fileList = [] } = this.data;
        fileList.splice(e.detail.index, 1)
        this.setData({ fileList })
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {

    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    }
})